package com.example.mybatisdemo.exception;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@ControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 处理参数验证异常
     * MethodArgumentNotValidException.class
     * 该类是spring框架的一个异常类
     * 在提交表单或API中提交的数据不符合验证规则时就会抛出这个异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<Map<String, Object>> handleValidationExceptions(MethodArgumentNotValidException ex, WebRequest request) {
        logger.error("参数验证失败: {}", ex.getMessage());
        
        List<FieldError> fieldErrors = ex.getBindingResult().getFieldErrors();
        String errorMessage = fieldErrors.stream()
                .map(error -> error.getField() + ": " + error.getDefaultMessage())
                .collect(Collectors.joining(", "));
        
        Map<String, Object> body = createErrorResponse(
                HttpStatus.BAD_REQUEST.value(),
                "参数验证失败",
                errorMessage,
                request
        );
        
        return new ResponseEntity<>(body, HttpStatus.BAD_REQUEST);
    }
    
    /**
     * 处理绑定异常
     */
    @ExceptionHandler(BindException.class)
    public ResponseEntity<Map<String, Object>> handleBindException(BindException ex, WebRequest request) {
        logger.error("参数绑定失败: {}", ex.getMessage());
        
        List<FieldError> fieldErrors = ex.getBindingResult().getFieldErrors();
        String errorMessage = fieldErrors.stream()
                .map(error -> error.getField() + ": " + error.getDefaultMessage())
                .collect(Collectors.joining(", "));
        
        Map<String, Object> body = createErrorResponse(
                HttpStatus.BAD_REQUEST.value(),
                "参数绑定失败",
                errorMessage,
                request
        );
        
        return new ResponseEntity<>(body, HttpStatus.BAD_REQUEST);
    }
    
    /**
     * 处理参数类型不匹配异常
     */
    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    public ResponseEntity<Map<String, Object>> handleMethodArgumentTypeMismatch(MethodArgumentTypeMismatchException ex, WebRequest request) {
        logger.error("参数类型不匹配: {}", ex.getMessage());
        
        String errorMessage = String.format("参数 '%s' 的值 '%s' 类型不匹配，应为 %s 类型", 
                ex.getName(), ex.getValue(), ex.getRequiredType().getSimpleName());
        
        Map<String, Object> body = createErrorResponse(
                HttpStatus.BAD_REQUEST.value(),
                "参数类型不匹配",
                errorMessage,
                request
        );
        
        return new ResponseEntity<>(body, HttpStatus.BAD_REQUEST);
    }
    
    /**
     * 处理缺少请求参数异常
     */
    @ExceptionHandler(MissingServletRequestParameterException.class)
    public ResponseEntity<Map<String, Object>> handleMissingServletRequestParameter(MissingServletRequestParameterException ex, WebRequest request) {
        logger.error("缺少请求参数: {}", ex.getMessage());
        
        String errorMessage = String.format("缺少必需的请求参数: '%s'，类型: %s", 
                ex.getParameterName(), ex.getParameterType());
        
        Map<String, Object> body = createErrorResponse(
                HttpStatus.BAD_REQUEST.value(),
                "缺少请求参数",
                errorMessage,
                request
        );
        
        return new ResponseEntity<>(body, HttpStatus.BAD_REQUEST);
    }
    
    /**
     * 处理请求方法不支持异常
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public ResponseEntity<Map<String, Object>> handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException ex, WebRequest request) {
        logger.error("请求方法不支持: {}", ex.getMessage());
        
        String errorMessage = String.format("请求方法 '%s' 不支持，支持的请求方法: %s", 
                ex.getMethod(), String.join(", ", ex.getSupportedHttpMethods().stream().map(Enum::name).collect(Collectors.toList())));
        
        Map<String, Object> body = createErrorResponse(
                HttpStatus.METHOD_NOT_ALLOWED.value(),
                "请求方法不支持",
                errorMessage,
                request
        );
        
        return new ResponseEntity<>(body, HttpStatus.METHOD_NOT_ALLOWED);
    }
    
    /**
     * 处理文件上传大小超限异常
     */
    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public ResponseEntity<Map<String, Object>> handleMaxUploadSizeExceededException(MaxUploadSizeExceededException ex, WebRequest request) {
        logger.error("文件上传大小超限: {}", ex.getMessage());
        
        Map<String, Object> body = createErrorResponse(
                HttpStatus.PAYLOAD_TOO_LARGE.value(),
                "文件上传大小超限",
                "上传的文件大小超过了允许的最大限制",
                request
        );
        
        return new ResponseEntity<>(body, HttpStatus.PAYLOAD_TOO_LARGE);
    }
    
    /**
     * 处理数据完整性违规异常
     */
    @ExceptionHandler(DataIntegrityViolationException.class)
    public ResponseEntity<Map<String, Object>> handleDataIntegrityViolationException(DataIntegrityViolationException ex, WebRequest request) {
        logger.error("数据完整性违规: {}", ex.getMessage());
        
        Map<String, Object> body = createErrorResponse(
                HttpStatus.CONFLICT.value(),
                "数据完整性违规",
                "操作违反了数据库的完整性约束",
                request
        );
        
        return new ResponseEntity<>(body, HttpStatus.CONFLICT);
    }
    
    /**
     * 处理唯一键冲突异常
     */
    @ExceptionHandler(DuplicateKeyException.class)
    public ResponseEntity<Map<String, Object>> handleDuplicateKeyException(DuplicateKeyException ex, WebRequest request) {
        logger.error("唯一键冲突: {}", ex.getMessage());
        
        Map<String, Object> body = createErrorResponse(
                HttpStatus.CONFLICT.value(),
                "唯一键冲突",
                "操作违反了唯一键约束",
                request
        );
        
        return new ResponseEntity<>(body, HttpStatus.CONFLICT);
    }
    
    /**
     * 处理非法参数异常
     */
    @ExceptionHandler(IllegalArgumentException.class)
    public ResponseEntity<Map<String, Object>> handleIllegalArgumentException(IllegalArgumentException ex, WebRequest request) {
        logger.error("参数错误: {}", ex.getMessage());

        Map<String, Object> body = createErrorResponse(
                HttpStatus.BAD_REQUEST.value(),
                "参数错误",
                ex.getMessage(),
                request
        );

        return new ResponseEntity<>(body, HttpStatus.BAD_REQUEST);
    }

    /**
     * 处理运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public ResponseEntity<Map<String, Object>> handleRuntimeException(RuntimeException ex, WebRequest request) {
        logger.error("运行时错误: {}", ex.getMessage());

        Map<String, Object> body = createErrorResponse(
                HttpStatus.INTERNAL_SERVER_ERROR.value(),
                "服务器错误",
                ex.getMessage(),
                request
        );

        return new ResponseEntity<>(body, HttpStatus.INTERNAL_SERVER_ERROR);
    }

    /**
     * 处理所有其他异常
     */
    @ExceptionHandler(Exception.class)
    public ResponseEntity<Map<String, Object>> handleAllExceptions(Exception ex, WebRequest request) {
        logger.error("未知错误: {}", ex.getMessage());

        Map<String, Object> body = createErrorResponse(
                HttpStatus.INTERNAL_SERVER_ERROR.value(),
                "未知错误",
                ex.getMessage(),
                request
        );

        return new ResponseEntity<>(body, HttpStatus.INTERNAL_SERVER_ERROR);
    }
    
    /**
     * 创建统一的错误响应格式
     */
    private Map<String, Object> createErrorResponse(int status, String error, String message, WebRequest request) {
        Map<String, Object> body = new HashMap<>();
        body.put("timestamp", new Date());
        body.put("status", status);
        body.put("error", error);
        body.put("message", message);
        body.put("path", request.getDescription(false).replace("uri=", ""));
        return body;
    }
}